<template>
  <div class="app-container">
    <el-row>
      <el-col :span="3" class="filter-cont">
        <el-input
          size="small"
          placeholder="输入关键字进行过滤"
          v-model="filterText"
        >
        </el-input>
        <el-tree
          class="filter-tree"
          :data="orgOptions"
          node-key="code"
          :props="defaultProps"
          :expand-on-click-node="false"
          default-expand-all
          :filter-node-method="filterNode"
          ref="origationTree"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </el-col>

      <el-col :span="21" class="right-cont">
        <el-col :span="11" class="left-width">
          <h4 class="list-title">运营平台设备信息</h4>
          <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
            @handleSelect="handleEomsSelect"
          >
            <template slot="address" slot-scope="scope">
              <el-tooltip :content="scope.row.address" placement="top">
                <span class="address">{{ scope.row.address }}</span>
              </el-tooltip>
            </template>
          </Table>
          <pagination
            v-if="total > 0"
            :total="total"
            :pageSizes="[15, 30, 45, 50, 200]"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
          />
        </el-col>
        <el-col :span="2" class="imports">
          <el-tooltip content="同步" placement="top">
            <el-button size="small" class="import_btn" @click="isImport(1)"
              >> ></el-button
            >
          </el-tooltip>
          <el-tooltip content="同步并设置运营商（一级组织）" placement="top">
            <el-button size="small" class="import_btn" @click="isImport(2)"
              >>>></el-button
            >
          </el-tooltip>
        </el-col>
        <el-col :span="11" class="left-width">
          <h4 class="list-title operate-title">
            日志升级平台设备信息
            <el-button
              type="primary"
              size="mini"
              class="add_btn set_btn"
              @click="isSets"
              >设置运营商<i class="el-icon-plus el-icon--right"></i
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              class="add_btn"
              @click="isAddTag"
              >设置标签<i class="el-icon-plus el-icon--right"></i
            ></el-button>
          </h4>

          <el-table
            border
            :header-cell-style="{
              padding: '2.5px 0',
              background: '#ECF1F7',
              textAlign: 'center',
            }"
            width="100%"
            ref="multipleTable"
            :data="energyData"
            :cell-style="{ textAlign: 'center' }"
            v-loading="energyLoading"
            @selection-change="handleSelect"
          >
            <el-table-column
              type="selection"
              width="40"
              fixed="left"
              :selectable="selectEnable"
            >
            </el-table-column>
            <el-table-column
              label="code"
              width="200"
              prop="code"
            ></el-table-column>
            <el-table-column label="地址" width="180" prop="address">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.address" placement="top">
                  <span class="address">{{ scope.row.address }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              label="经度"
              min-width="100"
              prop="lng"
            ></el-table-column>
            <el-table-column
              label="纬度"
              min-width="100"
              prop="lat"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-col>
    </el-row>

    <!-- 新增设备标签 -->
    <Dialog
      :visible="visible"
      width="26%"
      :loading="dialogBtnLoading"
      title="新增设备标签"
      @confirmDialog="submitDialogForm('dialogForm')"
      @cancelDialog="cancelDialog"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        label-width="70px"
        :rules="dialogRules"
      >
        <el-form-item label="已选设备">
          <div class="tags-data">
            <span
              v-for="(item, index) in selectData"
              :key="index"
              class="tag-one"
            >
              <el-tag v-if="index < 4">{{ item.code }}</el-tag></span
            >
          </div>
          <div class="more" v-if="selectData.length > 4">......等{{ selectData.length }}个设备</div>
        </el-form-item>
        <el-form-item label="标签" prop="tagsId">
          <el-radio-group v-model="dialogForm.tagsId">
            <el-radio
              class="tag-radio"
              :label="item.id"
              v-for="(item, index) in tagList"
              :key="index"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
          <el-button
            type="primary"
            size="mini"
            plain
            @click="tagVisible = true"
            class="add_tag_btn"
            icon="el-icon-plus"
          ></el-button>
        </el-form-item>
        <el-form
          v-show="tagVisible"
          class="tagForm"
          :inline="true"
          ref="tagForm"
          :model="tagForm"
          label-width="120px"
          :rules="tagRules"
          ><el-form-item prop="name">
            <el-input
              v-model="tagForm.name"
              placeholder="请输入标签名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            ><el-button type="primary" size="small" plain @click="isSubmitTag"
              >确定</el-button
            ><i class="el-icon-close" @click="tagVisible = false"></i
          ></el-form-item>
        </el-form>
      </el-form>
    </Dialog>
    <!--  同步并设置运营商（一级组织）弹框 -->
    <Dialog
      :visible="operateVisible"
      width="25%"
      :loading="dialogOperateLoading"
      title="同步并设置运营商（一级组织）"
      @confirmDialog="isChooseOperate"
      @cancelDialog="cancelChooseDialog"
    >
      <h3 class="list-title bind-title">绑定运营商（可输入）</h3>
      <el-form
        :model="operateForm"
        :rules="operateRules"
        ref="operateForm"
        class="operateForm"
      >
        <el-form-item prop="operateType">
          <el-radio-group v-model="operateForm.operateType">
            <el-radio
              class="radio-one"
              :label="1"
              @click.prevent.native="radioClick(1)"
              >{{ currentOrganization.name }}</el-radio
            ><br />
            <el-radio
              class="radio-one"
              :label="2"
              @click.prevent.native="radioClick(2)"
              ><el-input
                v-model="operateInput"
                placeholder="请输入运营商"
              ></el-input
            ></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </Dialog>

    <Dialog
      :visible="setOperateVisible"
      width="18%"
      :loading="setOperateLoading"
      title="设置运营商"
      class="operateDialog"
      @confirmDialog="isSetOperate"
      @cancelDialog="cancelSetDialog"
    >
      <div>
        <el-input
          v-model="setOperateName"
          placeholder="请输入运营商"
        ></el-input>
      </div>
    </Dialog>
  </div>
</template>
<script>
import { datasync } from "@/api/system";
import { removeNullUndefined } from "@/utils/index.js";
import { handleConfirm } from "@/utils/messageBox";

import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
export default {
  name: "EquipSync",
  components: { Pagination, Table, Dialog },
  data() {
    return {
      filterText: "",
      orgOptions: [],
      defaultProps: {
        children: "chrildens",
        label: "name",
      },
      tableHeader: [
        {
          type: "selection",
          width: "40",
          label: "多选",
          fixed: "left",
        },
        {
          label: "code",
          prop: "code",
          width: "200",
        },
        { slot: "address", label: "地址", width: "180" },
        {
          label: "经度",
          prop: "lng",
          width: "100",
        },
        {
          label: "纬度",
          prop: "lat",
          width: "100",
        },
      ],
      total: 0,
      tableData: [],
      listLoading: false,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        operateCode: "",
      },

      energyLoading: false,
      energyData: [],

      visible: false,
      dialogBtnLoading: false,
      dialogForm: {
        codes: "",
        tagsId: "",
      },
      dialogRules: {
        tagsId: [{ required: true, message: "请选择标签", trigger: "change" }],
      },
      tagList: [],
      tagForm: {
        name: "",
      },
      tagRules: {
        name: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
      },
      selectData: [], //选中data
      tagVisible: false,
      selectEomsData: [],

      // 选择运营商弹框
      operateVisible: false,
      dialogOperateLoading: false,
      currentOrganization: {}, //当前点击组织
      operateForm: { operateType: "" }, //组织机构
      operateInput: "",

      // 设置运营商
      setOperateName: "",
      setOperateLoading: false,
      setOperateVisible: false,
      operateRules: {
        operateType: [
          { required: true, message: "请选择运营商", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.origationTree.filter(val);
    },
  },
  created() {
    this.getOrgList();
  },
  methods: {
    // 获取所属组织机构
    async getOrgList() {
      let datas = await datasync("/operate/tree");
      if (datas.code == 200) {
        this.orgOptions = datas.data;
        let curOrgCode = datas.data.length > 0 ? datas.data[0].code : "";
        this.currentOrganization = datas.data.length > 0 ? datas.data[0] : {};
        this.searchForm.operateCode = curOrgCode;
        this.$nextTick(() => {
          this.$refs.origationTree.setCurrentKey(curOrgCode); //data[0].code为默认选中的节点
        });
        this.fetchData();
      }
    },
    fetchData() {
      this.listLoading = true;
      this.tableData = [];
      this.total = 0;

      this.energyData = [];
      this.selectEomsData = [];
      datasync(
        "/cabinet/list",
        "post",
        { ...removeNullUndefined(this.searchForm) },
        1
      )
        .then((res) => {
          this.tableData = res.data.records;
          this.total = +res.data.total;

          if (this.tableData.length > 0) {
            this.getEnergyList();
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleNodeClick(e, node) {
      let ancestors = [];
      // 如果节点是叶子节点，则将该节点的父级和祖先级数据依次加入数组
      if (!node.children || !node.children.length) {
        let parent = node.parent;
        while (parent) {
          ancestors.unshift(parent.data);
          parent = parent.parent;
        }
      } else {
        // 如果节点不是叶子节点，则将该节点的数据作为祖先级数据
        ancestors.push(node.data);
      }
      let root = ancestors.length > 1 ? ancestors[1] : node.data;
      this.currentOrganization = root;

      this.searchForm = {
        operateCode: root.code,
        pageNum: 1,
        pageSize: 15,
      };
      this.fetchData();
    },

    getEnergyList() {
      this.energyLoading = true;
      this.energyData = [];
      let codes = this.tableData.map((item) => {
        return item.code;
      });
      datasync("/energy/list", "post", codes)
        .then((res) => {
          let datas = res.data;
          let cloneArr1 = JSON.parse(JSON.stringify(this.tableData));
          cloneArr1.forEach((m) => {
            let inx = datas.findIndex((item) => item.code == m.code);
            if (inx != -1) {
              this.energyData.push(datas[inx]);
            } else {
              this.energyData.push({
                code: null,
                name: null,
                lng: null,
                lat: null,
                operatorName: null,
                address: null,
              });
            }
          });
        })
        .finally(() => {
          this.energyLoading = false;
        });
    },
    isAddTag() {
      if (this.energyData.length == 0) {
        this.$message.error("暂无设备！");
        return;
      }
      if (this.selectData.length == 0) {
        this.$message.error("请先选择设备！");
        return;
      }
      this.visible = true;
      this.getTagList();
    },
    // 查询全部标签
    async getTagList() {
      const data = await datasync("/tags/all");
      this.tagList = data.data;
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要给所选设备新增标签吗？`, "warning", "提示")
            .then((res) => {
              this.doAddTag();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    cancelDialog() {
      this.visible = false;
      this.dialogForm = {
        codes: "",
        tagsId: "",
      };
      this.tagForm = {
        name: "",
      };
      this.dialogBtnLoading = false;
    },
    doAddTag() {
      this.dialogBtnLoading = true;
      datasync(
        "/energy/insert/tags",
        "post",
        {
          codes: this.selectData
            .map((item) => {
              return item.code;
            })
            .join(","),
          tagsId: this.dialogForm.tagsId,
        },
        1
      ).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.cancelDialog();
          this.selectData = [];
          this.$refs.multipleTable.clearSelection();
        }
      }).finally(()=>this.dialogBtnLoading=false);
    },
    handleSelect(row, index) {
      this.selectData = row.filter((item) => item.code);
    },
    selectEnable(row, index) {
      if (row.code) {
        return true;
      } else {
        return false;
      }
    },
    handleEomsSelect(row) {
      this.selectEomsData = row;
    },
    isSubmitTag() {
      this.$refs["tagForm"].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要新增标签吗？`, "warning", "提示")
            .then((res) => {
              datasync(
                "/tags/insert",
                "post",
                { name: this.tagForm.name },
                1
              ).then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.tagVisible = false;
                  this.getTagList();
                }
              });
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    isImport(type) {
      // type 1:同步;2:同步并设置运营商（一级组织）;
      if (this.tableData.length == 0) {
        this.$message.error("暂无设备！");
        return;
      }
      if (this.selectEomsData.length == 0) {
        this.$message.error("请选择左侧需要导入的设备！");
        return;
      }
      if (type == 1) {
        handleConfirm(`确定要将已选设备导入日志升级平台吗？`, "warning", "提示")
          .then((res) => {
            // 比对code、address、lat、lng；若这四个字段值均相等，则过滤不导入
            let params = this.selectEomsData.map((m) => {
              let inx = this.energyData.findIndex(
                (item) => item.code == m.code
              );
              if (
                inx == -1 ||
                m.address != this.energyData[inx].address ||
                m.lat != this.energyData[inx].lat ||
                m.lng != this.energyData[inx].lng
              ) {
                return m;
              }
            });
            params = params.filter((pp) => pp && pp.code);
            if (params.length == 0) {
              this.$message.error("设备信息已同步，请重新选择设备！");
              return;
            }
            datasync("/save", "post", params).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.message);
                this.fetchData();
              }
            });
          })
          .catch((err) => {});
      } else {
        this.operateVisible = true;
        this.operateForm.operateType = 1;
      }
    },
    cancelChooseDialog() {
      this.operateVisible = false;
      this.operateForm.operateType = "";
      this.operateInput = "";
      this.operateForm.operateType = null;
    },
    isChooseOperate() {
      this.$refs["operateForm"].validate((valid) => {
        if (valid) {
          if (this.operateForm.operateType == 2 && !this.operateInput) {
            this.$message.error("请输入运营商");
            return;
          }
          handleConfirm(
            `确定要同步并设置运营商吗？`,
            "warning",
            "提示"
          )
            .then((res) => {
              this.doChooseOperate();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    doChooseOperate() {
      let operateName = null;
      operateName =
        this.operateForm.operateType == 1
          ? this.currentOrganization.name
          : this.operateInput;
      let params = JSON.parse(JSON.stringify(this.selectEomsData));
      // 比对code、address、lat、lng、operatorName；若这5个字段值均相等，则过滤不导入
      let selectData = params.map((m) => {
        let inx = this.energyData.findIndex((item) => item.code == m.code);
        if (
          inx == -1 ||
          m.address != this.energyData[inx].address ||
          m.operatorName != this.energyData[inx].operatorName ||
          m.lat != this.energyData[inx].lat ||
          m.lng != this.energyData[inx].lng
        ) {
          return m;
        }
      });
      // 将输入框中运营商赋进每一项
      if (operateName) {
        for (let i = 0; i < selectData.length; i++) {
          selectData[i].operatorName = operateName;
        }
      }
      this.dialogOperateLoading = true;
      datasync("/save", "post", selectData)
        .then((res) => {
          if (res.code == 200) {
            this.cancelChooseDialog();
            this.$message.success(res.message);
            this.fetchData();
          }
        })
        .finally(() => (this.dialogOperateLoading = false));
    },
    radioClick(type) {
      this.operateForm.operateType = type;
    },
    isSets() {
      if (this.energyData.length == 0) {
        this.$message.error("暂无设备！");
        return;
      }
      if (this.selectData.length == 0) {
        this.$message.error("请先选择设备！");
        return;
      }
      this.setOperateVisible = true;
    },
    cancelSetDialog() {
      this.setOperateVisible = false;
      this.setOperateName = "";
    },
    isSetOperate() {
      handleConfirm(`确认是否更改选中设备的运营商？`, "warning", "提示")
        .then((res) => {
          this.doSetOperate();
        })
        .catch((err) => {});
    },
    doSetOperate() {
      datasync("/update/operate", "post", {
        codes: this.selectData.map((item) => {
          return item.code;
        }),
        operateName: this.setOperateName,
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.cancelSetDialog();
          this.getEnergyList();
          this.selectData = [];
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/scss.scss";
.filter-tree {
  width: 100%;
  height: 85vh;
  overflow: auto;
  margin-top: 12px;
}
.filter-cont{
  width: 12%;
  margin-right: 1%;
}
.right-cont{
  width: 87%;
}
::v-deep .el-tree > .el-tree-node {
  display: inline-block;
  min-width: 100%;
}
::v-deep .el-tree-node.is-current > .el-tree-node__content {
  color: #fff;
  background: #5473e8;
}

::v-deep .el-tree-node {
  margin-top: 8px;
}
::v-deep .dialog-container .el-dialog__body {
  min-height: 240px;
}
::v-deep .operateDialog .el-dialog__body {
  min-height: 140px;
}
.list-title {
  text-align: center;
 
  .set_btn {
    margin-left: 10px;
  }
}
.operate-title{
  text-align: right;
  margin: 16px 0;
}
.bind-title {
  margin: 0 0 30px;
}
.address {
  display: inline-block;
  @include exceedFlow(1);
}
.tagForm {
  margin-left: 120px;
  .el-icon-close {
    margin-left: 20px;
    font-size: 24px;
    position: relative;
    top: 4px;
    color: #999;
  }
}
.add_tag_btn {
  margin-left: 10px;
}
.tags-data {
  @include exceedFlow(4);
  .tag-one {
    margin-left: 5px;
  }
}
.more{
  margin-left: 6px;
}
.radio-one {
  margin: 20px 0 0 50px;
}
.left-width{
  width: 46.3%;
}
.imports {
  width: 6.4%;
  text-align: center;
  .import_btn {
    margin-top: 70px;
    margin-left: 0;
  }
  .el-icon-arrow-right {
    color: #5473e8;
    font-weight: bold;
  }
}
::v-deep .operateForm .el-form-item__error {
  margin-left: 100px;
}
.tag-radio {
  margin-top: 14px;
}
</style>
